<template>
	<view class="rh-upload-container">
		<u-upload
			:fileList="fileList"
			@afterRead="afterRead"
			@delete="deletePic"
			:maxCount="maxCount"
			:mutiple="mutiple"
			width="180"
			height="180"
		>
			<view class="upload-content">
				<u-icon name="plus"></u-icon>
			</view>
		</u-upload>
		<view v-if="canvasList.length" style="position: absolute;top: -999999px;">
			<view v-for="(canvas, index) in canvasList" :key="index">
				<canvas :style="{ width: canvas.w, height: canvas.h }" :canvas-id="canvas.id"></canvas>
			</view>
		</view>
	</view>
</template>

<script>
	import {getDateTime} from '@/script/tools.js';
	import {getToken} from '@/utils/auth.js'
	import {apiUrl_config} from '@/config.js'
	import {mapActions, mapGetters} from 'vuex'
	export default {
		computed: {
			...mapGetters('location', ['currentLocation'])
		},
		props: {
			value: [Array],
			maxCount: {
				type: Number,
				default: () => {return 3}
			},
			water: {
				type: Boolean,
				default: () => true
			},
			mutiple: {
				type: Boolean,
				default: () => true
			},
		},
		watch: {
			value(val){
				if(val){
					this.fileList = []
					val.forEach(file => {
						let url = ''
						if (file['url'].indexOf(this.baseUrl) === -1) {
							url = this.baseUrl + file.url
						} else {
							url = file.url
						}
						this.fileList.push({
							status: 'success',
							message: '',
							url: url,
							id: file.fileId || file.id
						})
					})
				}
			},
		},
		data() {
			return {
				https: process.env['APIURL_CONFIG'] + '/api/system/common/uploadFile',
				baseUrl: apiUrl_config,
				fileList: [],
				header:{
					'RH-Toilet-Token':getToken()
				},
				canvasList: []
			};
		},
		methods: {
			// 删除图片
			deletePic(event) {
				let arr = JSON.parse(JSON.stringify(this.value))
				this[`fileList`].splice(event.index, 1)
				arr.splice(event.index, 1)
				this.$emit('input', arr)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let _self = this
				let lists = [].concat(event.file)
				console.log(event.file)
				let fileListLen = this[`fileList`].length
				lists.map((item) => {
					this[`fileList`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				if(this.water ){
					let arr = this.mutiple ? event.file : [event.file]
					await Promise.all(_self.drawWater(arr))
					_self.canvasList = []
				}
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList`][fileListLen]
					this[`fileList`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.path,
						id: result.id
					}))
					fileListLen++
					this.$emit('input', this.fileList)
				}
			},
			uploadFilePromise(url) {
				let _self = this
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: _self.https, // 仅为示例，非真实的接口地址
						header: _self.header,
						filePath: url,
						name: 'file',
						success: (res) => {
							res = JSON.parse(res.data) 
							console.log(res.data)
							setTimeout(() => {
								resolve(res.data)
							}, 1000)
						}
					});
				})
			},
			drawWater(list){
				let that = this, arr = []
				that.canvasList = []
				let fn = (pic, idx) => {
					return new Promise((resolve, reject) => {
						uni.getImageInfo({
							src: pic.url,
							success: res => {
								let source = {
									w: 640,
									height: 360
								}
								that.canvasList.push({
									w: res.width + 'px',
									h: res.height + 'px',
									id: `uniCanvas_${idx + 1}`
								})
								let ctx = uni.createCanvasContext(that.canvasList[idx]['id'], this); /** 创建画布 */
								//将图片src放到cancas内，宽高为图片大小
								ctx.drawImage(pic.thumb, 0, 0, res.width, res.height);
								
								ctx.setFontSize(10 * res.width / source.w)
								ctx.setFillStyle('rgba(256, 256, 256, 0.8)')
								ctx.shadowColor = 'rgba(256, 256, 256, 0.8)'
								
								let textToWidth = (res.width) * 0.03;
						
								let textToHeight = (res.height) * 0.86;
								ctx.fillText(`时间：${getDateTime('y年m月d日 h:i:s')}`, textToWidth, textToHeight);
						
								let textToHeight2 = (res.height) * 0.9;
								ctx.fillText(`地点：${that.currentLocation['name']}${that.currentLocation['desc']}`, textToWidth, textToHeight2);
						
								let textToHeight3 = (res.height) * 0.94;
								ctx.fillText(`经度：${that.currentLocation['longitude']}`, textToWidth, textToHeight3);
								
								let textToHeight4 = (res.height) * 0.98;
								ctx.fillText(`纬度：${that.currentLocation['latitude']}`, textToWidth, textToHeight4);
								ctx.draw(false, () => {
									setTimeout(() => {
										uni.canvasToTempFilePath({
											canvasId: that.canvasList[idx]['id'],
											fileType: 'jpg',
											destWidth: res.width,
											destHeight: res.height,
											success: ress => {
												console.log(ress.tempFilePath, 666666)
												uni.getFileInfo({
													filePath: ress.tempFilePath,
													success:imgInfo=>{
														console.log(imgInfo.size, 99999);
													}
												})
												pic.thumb = ress.tempFilePath
												pic.url = ress.tempFilePath
												resolve(pic)
											},
											fail: (err) => {
												reject(err)
											}
										}, this);
									}, 300);
								});
							}
						});
					})
				}
				list.length ? '' : list = [list]
				list.forEach((pic, index) => {
					arr.push(fn(pic, index))
				})
				return arr
			}
		},
	}
</script>

<style lang="scss">
.upload-content{
	display: flex;
	width: 180rpx;
	height: 180rpx;
	border: 2rpx dashed #ccc;
	border-radius: 10rpx;
	overflow: hidden;
	justify-content: center;
}
</style>
